package cn.top.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.top.system.entity.User;
import cn.top.system.mapper.SysRoleMapper;
import cn.top.system.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(username), User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名密码错误");
        }
/*        List<String> perssions = Arrays.asList("test", "aaa", "admin");
        user.setPerssions(perssions);*/

        List<String> roles = roleMapper.getRoleByUserId(user.getId());
        user.setPerssions(roles);
        return user;
    }
}
